# 中间件
import datetime

from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models


class Tracer(object):
    """自定义类, 用于在request中赋值"""

    def __init__(self):
        self.user = None
        self.price_policy = None
        self.project = None


class AuthMiddleware(MiddlewareMixin):
    """登录认证中间件"""

    def process_request(self, request):
        # 如果用户登录, 则在request中赋值

        request.tracer = Tracer()

        user_id = request.session.get('user_id', 0)
        user_obj = models.UserInfo.objects.filter(id=user_id).first()

        request.tracer.user = user_obj

        # 检查用户是否登录, 已登录则放行, 未登录则跳转到登录页面
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return

        if not request.tracer.user:
            return redirect('/login/sms/')

        # 登陆成功后, 访问后台管理时: 获取用户拥有的额度
        # 获取当前用户ID最大, 最近的额度记录
        _object = models.Transaction.objects.filter(user=user_obj, status=2).order_by('-id').first()
        # 判断是否已经过期
        if _object.end_datetime and _object.end_datetime < datetime.datetime.now():
            _object = models.Transaction.objects.filter(user=user_obj, status=2, price_policy__category=1).first()

        # 将额度记录赋值给request.price_policy
        request.tracer.price_policy = _object.price_policy

    def process_view(self, request, view, args, kwargs):
        """
        :param request:
        :param view:
        :param args:
        :param kwargs:
        :return:
        """
        # 判断url是否以manage开头, 如果是则判断project_id
        if not request.path_info.startswith('/manage/'):
            return
        # project_id 是我创建的 or 我参与的
        project_id = kwargs.get('project_id')
        user = request.tracer.user
        project_obj = models.Project.objects.filter(creator=user, id=project_id).first()
        if project_obj:
            # 属于我创建的项目, 通过
            request.tracer.project = project_obj
            return
        project_user_obj = models.ProjectUser.objects.filter(user=user, project_id=project_id).first()
        if project_user_obj:
            # 属于我参与的项目, 通过
            request.tracer.project = project_user_obj
            return
        # 不满足以上条件, 不通过, 并返回项目列表页面
        return redirect('project_list')


